<template>
  <div>
    <!-- 面包屑导航区 -->
    <bread-nav>
      <span slot="c1">商品管理</span>
      <span slot="c2">编辑商品</span>
    </bread-nav>

    <!-- 卡片视图区 -->
    <el-card>
      <el-alert
        title="编辑商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      ></el-alert>
      <!-- 步骤条 -->
      <el-steps
        class="steps"
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editRuleFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          class="tab"
          v-model="activeIndex"
          :before-leave="beforeLeave"
          @tab-click="tabHandleClick"
          tabPosition="left"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="editForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="editForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight" type="number">
              <el-input v-model="editForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="editForm.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                :options="cateList"
                v-model="editForm.goods_cat"
                @change="handleChange"
                :props="{
                  // 看到的值
                  label: 'cat_name',
                  // 选中的值
                  value: 'cat_id',
                  children: 'children',
                  expandTrigger: 'hover',
                }"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in manyTableData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(val, i) in item.attr_vals"
                  :label="val"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyTableData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals" />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :headers="headersObj"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="handleSuccess"
              :file-list="editForm.pics"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="editForm.goods_introduce"></quill-editor>
            <!-- 添加商品按钮 -->
            <el-button class="addBtn" type="primary" @click="addGoods"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览区 -->
    <el-dialog
      title="图片预览"
      :visible.sync="priviewVisble"
      width="50%"
      :before-close="handleClose"
    >
      <img :src="previewPath" alt="" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import BreadNav from 'components/content/nav/BreadNav.vue'
import {
  queryGoodsById,
  getGoodsCategory,
  getGoodsAttributtes,
  editGoodsReq,
} from 'network/goods.js'
export default {
  name: 'EditGoods',
  components: { BreadNav },
  data() {
    return {
      //接收的 id
      id: '',
      activeIndex: 0,
      // 编辑表单数据对象
      editForm: {},
      // 商品分类列表数据
      cateList: [],
      // 动态参数列表
      manyTableData: [],
      // 静态属性列表
      onlyTableData: [],
      // 网络请求组件的headerd请求头对象
      headersObj: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      // 图片地址
      previewPath: '',
      // 图片预览框
      priviewVisble: false,
      // 编辑表单验证规则
      editFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
        goods_cat: [
          { required: true, message: '请选中商品分类', trigger: 'blur' },
        ],
      },
    }
  },

  created() {
    this.getEditGoodsData()
    this.getGoodsCateList()
  },
  methods: {
    // 根据id获取要编辑商品的数据
    async getEditGoodsData() {
      const { data: res } = await queryGoodsById(this.$store.state.goodsId)
      if (res.meta.status !== 200) {
        this.$message.error('获取商品数据失败，返回重试！')
        return
      }
      // 处理 goods_cat 把字符串转化为数字并放入数组里面
      const goos_catArr = res.data.goods_cat.split(',')
      let newGoods_cat = goos_catArr.map((item) => {
        return item - 0
      })
      res.data.goods_cat = newGoods_cat
      this.editForm = res.data
    },
    // 获取商品分类列表
    async getGoodsCateList() {
      const { data: res } = await getGoodsCategory()
      if (res.meta.status !== 200) {
        this.$message.error('获取商品分类失败！')
        return
      }
      this.cateList = res.data
    },
    // 点击tab栏跳转前触发函数
    beforeLeave() {},
    // 点击tab栏时触发函数
    async tabHandleClick() {
      if (this.activeIndex === '1') {
        const { data: res } = await getGoodsAttributtes(
          this.editForm.goods_cat[2],
          'many'
        )
        if (res.meta.status !== 200) {
          this.$message.error('获取商品参数失败！')
          return
        }
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await getGoodsAttributtes(
          this.editForm.goods_cat[2],
          'only'
        )
        if (res.meta.status !== 200) {
          this.$message.error('获取商品参数失败！')
          return
        }
        this.onlyTableData = res.data
      }
    },
    // 级联选中项变化触发函数
    handleChange() {
      if (this.editForm.goods_cat.length !== 3) {
        this.editForm.goods_cat = []
      }
    },
    // 图片预览函数
    handlePreview(file) {
      console.log(file)
      this.previewPath = file.response.data.url
      this.priviewVisble = true
    },
    handleRemove(file) {
      // 1. 获取要移除图片的路径
      const filePath = file.pic
      // 2. 从 pic 数组中，找到这个图片对应的索引值
      const i = this.editForm.pics.findIndex((x) => x.pic === filePath)
      // 3. 调用数组的 splice 方法，把图片信息对象，从pic数组中移除
      this.editForm.pics.splice(i, 1)

      this.$message.success('图片删除成功！')
    },
    // 图片上传成功事件
    handleSuccess(response) {
      const picInfo = { pic: response.data.tmp_path }
      this.editForm.pics.push(picInfo)
      this.$message.success('图片上传成功！')
    },
    // 图片预览框关闭函数
    handleClose() {
      this.priviewVisble = false
    },
    // 添加商品按钮函数
    addGoods() {
      this.$refs.editRuleFormRef.validate(async (valid) => {
        if (!valid) {
          this.$message.error('请填写必要的表单项！')
          return
        }

        // 执行添加业务逻辑
        // 深拷贝
        const form = _.cloneDeep(this.editForm)
        form.goods_cat = form.goods_cat.join(',')

        // 处理动态参数
        this.manyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' '),
          }
          this.editForm.attr.push(newInfo)
        })
        // 处理静态属性
        this.onlyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          }
          this.editForm.attr.push(newInfo)
        })
        form.attr = this.editForm.attr
        const { data: res } = await editGoodsReq(
          form,
          this.$store.state.goodsId
        )
        if (res.meta.status !== 200) {
          this.$message.error('编辑商品失败' + res.meta.msg + '！')
          return
        }
        this.$message.success('编辑商品成功！')
        this.$router.push('/goods')
      })
    },
  },
}
</script>

<style scoped>
</style>